package com.easy.component.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;

import com.easy.component.R;
import com.easy.component.component.toast.EasyToast;
import com.easy.component.network.EasyHttpManager;
import com.easy.component.network.callback.CallBack;
import com.easy.component.network.exception.ApiException;

import java.io.File;
import java.util.UUID;

public class UpdateService extends Service {
    public static final String UPDATE_APK_INSTALL = "update_apk_install";
    public static final String UPDATE_CHANNEL = "update_channel_reversetreasure";
    public static final String UPDATE_CHANNEL_PROGRESS = "update_channel_reversetreasure_progress";
    public static final String UPDATE_APK_INSTALL_PROGRESS = "update_apk_install_progress";
    private NotificationCompat.Builder mBuilder;
    private String mChannelId;
    private String mChannelName;
    private String mFile;
    /**
     * 通知管理类
     */
    private NotificationManager mNotificationManager;
    /**
     * 通知ID
     */
    private int mId = -1;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancelAll();
        if (mFile == null || "".equals(mFile.trim())) {
            createNotification(0, 0, true, "正在下载");
            try {
                String newApkurl = intent.getStringExtra("url");
                String destFileDir = Environment.getExternalStorageDirectory() + "";
                String destFileName = getPackageName() + Math.abs(UUID.randomUUID().hashCode()) + ".apk";
                new EasyHttpManager(newApkurl).download(destFileDir, destFileName, ajaxCallBack);
            } catch (Exception e) {
                createNotification(0, 0, true, "下载失败");
            }
        } else {
            createNotification(0, 0, true, "下载完成", getInstallIntent(mFile));
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void createNotification(int max, int progress, boolean indeterminate, String content) {
        createNotification(max, progress, indeterminate, content,
                null, UPDATE_CHANNEL, UPDATE_APK_INSTALL);
    }

    private void createNotification(int max, int progress, boolean indeterminate, String content, PendingIntent intent) {
        createNotification(max, progress, indeterminate, content,
                intent, UPDATE_CHANNEL, UPDATE_APK_INSTALL);
    }

    private void createNotification(int max, int progress, boolean indeterminate, String content,
                                    PendingIntent intent, String channelId, String channelName) {

        if (!channelId.equals(mChannelId) || !channelName.equals(mChannelName)) {
            mBuilder = null;
            mChannelId = channelId;
            mChannelName = channelName;
        }

        if (mBuilder == null) {
            if (mId > 0) {
                mNotificationManager.cancel(mId);
            }
            mId = Math.abs(UUID.randomUUID().hashCode());
            mBuilder = new NotificationCompat.Builder(this, channelId);
        }


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = null;
            if (!UPDATE_APK_INSTALL_PROGRESS.equals(channelName)) {
                channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
                channel.enableLights(true);
                channel.enableVibration(true);
                channel.setVibrationPattern(new long[]{100, 200, 300, 400});
            } else {
                channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
                channel.enableLights(false);
                channel.enableVibration(false);
                channel.setSound(null, null);
            }
            channel.setDescription(channelName);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            mNotificationManager.createNotificationChannel(channel);


        }
        mBuilder.setProgress(max, progress, indeterminate).
                setSmallIcon(R.drawable.ic_launcher).
                setAutoCancel(true).
                setContentText(content).
                setVisibility(NotificationCompat.VISIBILITY_PRIVATE);

        if (!UPDATE_APK_INSTALL_PROGRESS.equals(channelName)) {
            mBuilder.setWhen(System.currentTimeMillis()).
                    setTicker(content).
                    setPriority(Notification.PRIORITY_HIGH).
                    setDefaults(Notification.DEFAULT_ALL);
        }
        if (intent != null) {
            mBuilder.setFullScreenIntent(intent, true);
        }

        mNotificationManager.notify(mId, mBuilder.build());
    }

    private final CallBack<String> ajaxCallBack = new CallBack<String>() {
        long beforTime;

        @Override
        public void onLoading(int progress) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - beforTime) > 50) {
                createNotification(100, progress, true, progress + "%",
                        null, UPDATE_CHANNEL_PROGRESS, UPDATE_APK_INSTALL_PROGRESS);
            }
            beforTime = System.currentTimeMillis();
        }

        @Override
        public void onError(ApiException e) {

        }

        @Override
        public void onSuccess(String file) {
            mFile = file;
            createNotification(0, 0, true, "下载完成", getInstallIntent(file));
            try {
                installApk(file);
            } catch (Exception e) {
                EasyToast.showLong(UpdateService.this, "安装失败");
            }
        }

        @Override
        public void onError() {
            createNotification(0, 0, true, "下载失败");
        }

        @Override
        public void onLoinError() {

        }
    };

    /**
     * 用户手动点击安装apk文件
     *
     * @return PendingIntent
     */
    private PendingIntent getInstallIntent(String filePath) {
        Uri uri = getProviderPath(this, new File(filePath));
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        return PendingIntent.getActivity(this, 0, installIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    }


    /**
     * 安装apk
     *
     * @param filePath 安装路径
     */
    private void installApk(String filePath) {
        Uri uri = getProviderPath(this, new File(filePath));
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivity(installIntent);

    }

    /**
     * 获取FileProvider路径
     */
    public static Uri getProviderPath(Context context, File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(context, "com.zhineng.reversetreasure.fileprovider", file);
        } else {
            return Uri.fromFile(file);
        }

    }
}
